<template>
    <div class="login-view"  ><h1 style=" position: fixed; left: 100px; top:30px; font-weight: bold;
    font-size: 36px;
    color: #1675EA;
    text-decoration: none;
     text-shadow: 0px 0px 4px #d9eef3">        <img src="../assets/image/indexlogo.png" style="width: 200px">
    </h1>
        <div class="login-content">
            <div class="login-intro">
                <img src="../assets/image/login-pic.png" width="100%"  style="min-width: 450px;"/>
            </div>
            <el-form class="login-form" :model="loginForm" status-icon :rules="rules" ref="loginForm" :label-position="labelPosition" label-width="70px"
                     @keyup.enter.native="submitForm('loginForm')">

                <el-tabs  @tab-click="handleClick" v-model="activeName">
                    <el-tab-pane label="UKey登录" name="first"   >
                        <el-form-item label="储存介质" prop="CryptProv"  >
                            <el-select v-model="loginForm.CryptProv" placeholder="请选择储存介质" style="width:100%;">
                                <el-option
                                        v-for="item in ukeyoptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="用户名" prop="keyUserName">
                            <el-input type="keyUserName" v-model="loginForm.keyUserName" ref="keyUserName"
                                      placeholder="请输入用户名"></el-input>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="keysubmitForm('loginForm')"  style="width: 100%; height: 44px; background: #4096FF;">登录</el-button>

                        </el-form-item>

                    </el-tab-pane>



                    <el-tab-pane label="口令登录" name="second" v-if="false">

                        <el-form-item label="终端" prop="userName" v-show="false"  >
                            <el-input type="terminal" v-model="loginForm.terminal" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="账号" prop="userName">
                            <el-input type="userName" v-model="loginForm.userName" autocomplete="off"
                                      placeholder="账号"></el-input>

                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input type="password" v-model="loginForm.password" autocomplete="off"
                                      placeholder="密码"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitForm('loginForm')"  style="width: 100%; height: 44px; background: #4096FF;">登录</el-button>
                        </el-form-item></el-tab-pane>
                </el-tabs>
            </el-form>
        </div>
        <icp></icp>
    </div>

</template>
<script>
    import Icp from '../components/common/Icp.vue'
    import { isEmpty} from '@/utils/talkmeet'
    import { initProv, readUKSN, genRandom, signatureWithAlg } from '@/utils/zwPlugin'


    export default {
        name: "login",
        components: {
            Icp
        },
        data() {
            var checkUsername = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入账号'));
                }
                callback();
            };
            var checkPassword = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                }
                callback();

            };
            var checkKeyUsername = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入用户名'));
                }
                callback();
            };
            return {
                // 签名算法：SM2WithSM3
                algSign: 3,
                loginModle:'',
                serverRandom:'',
                activeName: 'first',
                labelPosition: 'top',
                loginForm: {
                    terminal: this.$enums.TERMINAL_TYPE.WEB,
                    userName: '',
                    password: '',
                    keyUserName:'',
                    CryptProv:''
                },
                rules: {
                    keyUserName: [{
                        required: true,
                        validator: checkKeyUsername,
                        trigger: 'blur'
                    }],
                    userName: [{
                        required: true,
                        validator: checkUsername,
                        trigger: 'blur'
                    }],
                    password: [{
                        required: true,
                        validator: checkPassword,
                        trigger: 'blur'
                    }],
                    CryptProv:[{
                        required: true,
                        message: '请选择存储介质',
                        trigger: 'change'
                    }]
                },
                ukeyoptions: [{
                    value: 'Longmai mToken GM3000 CSP V1.1',
                    label: '龙脉'
                }],
            };
        },
        methods: {
            //meiju
            enumProviders(){
                console.log("---------enumid------");
                let a = window.test('this is good')
                console.log(a);
                /*var CryptProv = window.document.getElementById("CryptProv");
                window.enumProvider(CryptProv);*/
                return a;

            },
            handleClick(tab, event) {
                console.log("---------------"+JSON.stringify(tab.name), event);
                this.loginModle = tab.name;
            },
            submitForm(formName) {
                //存放校验结果
                let validList = [];
                this.$refs[formName].validateField(['userName','password'],(valid) => {
                //this.$refs[formName].validate((valid) => {
                    if (!valid){
                        //校验成功后，将结果保存到validList
                        validList.push(valid)
                    }
                    if (validList.length == 2 && validList.every(item => item === '')) {
                        this.$http({
                            url: "/login",
                            method: 'post',
                            data: this.loginForm
                        }).then((data) => {
                            console.log("login:"+JSON.stringify(data));
                                // 保存密码到cookie(不安全)
                                this.setCookie('username', this.loginForm.userName);
                                this.setCookie('password', this.loginForm.password);
                                // 保存token
                                sessionStorage.setItem("accessToken", data.accessToken);
                                sessionStorage.setItem("refreshToken", data.refreshToken);
                                //保存权限信息
                                sessionStorage.setItem("permissionList", data.permissionList);
                                this.$message.success("登录成功");
                                this.$router.push("/home/chat");
                        })
                    }
                });
            },
            keysubmitForm(formName) {
                console.log("window.electronAPI:"+JSON.stringify(window.electronAPI))
                console.log("electronAPI:"+window.electronAPI)
                //this.exekeysubmitForm(formName)//exe登录
                //this.webkeysubmitForm(formName)//web登录
                if (window.electronAPI) {
                    console.log("exe登录")
                    this.exekeysubmitForm(formName)//exe登录
                } else {
                    console.log("web登录")
                    this.webkeysubmitForm(formName)//web登录
                }
            },
            async exekeysubmitForm(formName) {
                //龙脉使用的v2.0.7.2版本
                let CONT_NAME = "CCITCont1"
                let provName = "Longmai mToken GM3000 CSP V1.1"
                //存放校验结果
                let validList = [];
                this.$refs[formName].validateField(['CryptProv','keyUserName'],(valid) => {
                    if (!valid){
                        //校验成功后，将结果保存到validList
                        validList.push(valid)
                    }
                });
                //const result = await this.init();
                //console.log(".22222222............"+result); // 处理Promise解析的数据
                if (validList.length == 2 && validList.every(item => item === '')) {
                    var keyUserName = this.loginForm.keyUserName;
                    //0.初始化
                    var ret =  await window.electronAPI.initProv(provName, CONT_NAME);
                    console.log('vue 初始化设备失败结果：'+ret)
                    if (!ret) {
                        console.log('初始化设备失败')
                        return false;
                    }else {
                        console.log('初始化设备成功')
                    }
                      // 1.获取uk序列号
                      const deviceSN = await window.electronAPI.readUKSN();
                      console.log('vue 获取uk序列号结果deviceSN:'+deviceSN)
                      if (isEmpty(deviceSN)) {
                          return false;
                      }
                      // 2.获取ukey获取随机数
                     var ukeyRandomNum = await window.electronAPI.genRandom(16);
                     console.log("ukeyRandomNum:" + ukeyRandomNum)
                     if (isEmpty(ukeyRandomNum)) {
                         return false;
                     }
                     // 3.获取服务端随机数
                    console.log("=====开始获取服务器随机数结果=======")
                    let data = await this.$http({
                        url: '/random?ukeyRandom=' + encodeURIComponent(ukeyRandomNum),
                        method: 'get',
                        data: ''
                     })
                    console.log("=====获取服务器随机数结果======="+JSON.stringify( data.random))
                    //4.发送验证签名数据
                    const srcData = ukeyRandomNum + "," + deviceSN + "," + data.random;
                    console.log('srcData:' + srcData);
                    const signValue = await window.electronAPI.signatureWithAlg(srcData, this.algSign);
                    if (signValue == null || signValue.length == 0 ||signValue.success ==false) {
                        console.log('签名失败！')
                        this.$refs.keyUserName.focus();
                        return false;
                    }
                    // 如果点击取消那么签名值为空，直接返回
                    console.log('signData: ' + JSON.stringify(signValue));
                    if (isEmpty(signValue.data)) {
                        return false;
                    }
                    var loginData = {
                        'userName': keyUserName,
                        'deviceSN': deviceSN,
                        'signData': signValue.data,
                        'random': ukeyRandomNum,
                        'terminal': this.loginForm.terminal
                    };
                    this.$http({
                        url: "/certLogin",
                        method: 'post',
                        data: loginData
                    }).then((data) => {
                        console.log("证书登录结果：" + JSON.stringify(data))
                        // 保存密码到cookie(不安全)
                        this.setCookie('username', this.loginForm.userName);
                        this.setCookie('password', this.loginForm.password);
                        //保存权限信息
                        sessionStorage.setItem("permissionList", data.permissionList);
                        // 保存token
                        sessionStorage.setItem("accessToken", data.accessToken);
                        sessionStorage.setItem("refreshToken", data.refreshToken);
                        this.$message.success("登录成功");
                        this.$router.push("/home/chat");
                    })

                    /*this.$http({
                         url: '/random?ukeyRandom=' + encodeURIComponent(ukeyRandomNum),
                         method: 'get',
                         data: ''
                     }).then((data) => {
                         console.log("=====获取随机数结果======="+JSON.stringify( data.random))*/
                         //4.发送验证签名数据
                         /*const srcData = ukeyRandomNum + "," + deviceSN + "," + data.random;
                         console.log('srcData:' + srcData);
                         const signValue = window.electronAPI.signatureWithAlg(srcData, this.algSign);
                         if (signValue == null || signValue.length == 0) {
                             console.log('签名失败！')
                             this.$refs.keyUserName.focus();
                             return false;
                         }
                         // 如果点击取消那么签名值为空，直接返回
                         console.log('signData: ' + signValue);
                         if (isEmpty(signValue)) {
                             return false;
                         }
                         var loginData = {
                             'userName': keyUserName,
                             'deviceSN': deviceSN,
                             'signData': signValue,
                             'random': ukeyRandomNum,
                             'terminal': this.loginForm.terminal
                         };
                         this.$http({
                             url: "/certLogin",
                             method: 'post',
                             data: loginData
                         }).then((data) => {
                             console.log("证书登录结果：" + JSON.stringify(data))
                             // 保存密码到cookie(不安全)
                             this.setCookie('username', this.loginForm.userName);
                             this.setCookie('password', this.loginForm.password);
                             //保存权限信息
                             sessionStorage.setItem("permissionList", data.permissionList);
                             // 保存token
                             sessionStorage.setItem("accessToken", data.accessToken);
                             sessionStorage.setItem("refreshToken", data.refreshToken);
                             this.$message.success("登录成功");
                             this.$router.push("/home/chat");
                         })*/
                    /* })*/
                }
            },
            webkeysubmitForm(formName) {
                //龙脉使用的v2.0.7.2版本
                let CONT_NAME = "CCITCont1"
                let provName = "Longmai mToken GM3000 CSP V1.1"
                //存放校验结果
                let validList = [];
                this.$refs[formName].validateField(['CryptProv','keyUserName'],(valid) => {
                    if (!valid){
                        //校验成功后，将结果保存到validList
                        validList.push(valid)
                    }
                    if (validList.length == 2 && validList.every(item => item === '')) {
                            var keyUserName = this.loginForm.keyUserName;
                            //0.初始化
                            var ret = initProv(provName, CONT_NAME);
                            if (!ret) {
                                console.log('初始化设备失败')
                                return false;
                            }
                            // 1.获取uk序列号
                            const deviceSN = readUKSN();
                            if (isEmpty(deviceSN)) {
                                return false;
                            }
                            // 2.获取ukey获取随机数
                            var ukeyRandomNum = genRandom(16);
                            console.log("ukeyRandomNum:" + ukeyRandomNum)
                            if (isEmpty(ukeyRandomNum)) {
                                return false;
                            }
                            // 3.获取服务端随机数
                            this.$http({
                                url: '/random?ukeyRandom=' + encodeURIComponent(ukeyRandomNum),
                                method: 'get',
                                data: ''
                            }).then((data) => {
                                console.log("=====获取随机数结果======="+JSON.stringify( data.random))
                                //4.发送验证签名数据
                                const srcData = ukeyRandomNum + "," + deviceSN + "," + data.random;
                                console.log('srcData:' + srcData);
                                const signValue = signatureWithAlg(srcData, this.algSign);
                                if (signValue == null || signValue.length == 0) {
                                    console.log('签名失败！')
                                    this.$refs.keyUserName.focus();
                                    return false;
                                }
                                // 如果点击取消那么签名值为空，直接返回
                                console.log('signData: ' + signValue);
                                if (isEmpty(signValue)) {
                                    return false;
                                }
                                var loginData = {
                                    'userName': keyUserName,
                                    'deviceSN': deviceSN,
                                    'signData': signValue,
                                    'random': ukeyRandomNum,
                                    'terminal': this.loginForm.terminal
                                };
                                this.$http({
                                    url: "/certLogin",
                                    method: 'post',
                                    data: loginData
                                }).then((data) => {
                                    console.log("证书登录结果：" + JSON.stringify(data))
                                    // 保存密码到cookie(不安全)
                                    this.setCookie('username', this.loginForm.userName);
                                    this.setCookie('password', this.loginForm.password);
                                    //保存权限信息
                                    sessionStorage.setItem("permissionList", data.permissionList);
                                    // 保存token
                                    sessionStorage.setItem("accessToken", data.accessToken);
                                    sessionStorage.setItem("refreshToken", data.refreshToken);
                                    this.$message.success("登录成功");
                                    this.$router.push("/home/chat");
                                })
                            })
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            // 获取cookie、
            getCookie(name) {
                let reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
                let arr = document.cookie.match(reg)
                if (arr) {
                    return unescape(arr[2]);
                }
                return '';
            },
            // 设置cookie,增加到vue实例方便全局调用
            setCookie(name, value, expiredays) {
                var exdate = new Date();
                exdate.setDate(exdate.getDate() + expiredays);
                document.cookie = name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate
                    .toGMTString());
            },
            // 删除cookie
            delCookie(name) {
                var exp = new Date();
                exp.setTime(exp.getTime() - 1);
                var cval = this.getCookie(name);
                if (cval != null) {
                    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
                }
            }
        },
        mounted() {
            this.loginForm.userName = this.getCookie("username");
            // cookie存密码并不安全，暂时是为了方便
            this.loginForm.password = this.getCookie("password");
            // 确保在组件挂载后加载第三方JS
            /*const script = document.createElement('script');
            script.src = process.env.BASE_URL +'zwPlugin.js';
            script.onload = () => {
            // 第三方脚本加载完成后的回调
            console.log('第三方脚本加载完成');
            };
            document.head.appendChild(script);*/
        },
    }
</script>

<style scoped lang="scss">

  .login-view {
    width: 100%;
    height: 100%;
    background-image:url('../assets/image/login-bg.jpg');
    background-size: 100% 100%;
    box-sizing: border-box;


    .login-content {
      position: relative;
      display: flex;
      justify-content: space-around;
      align-items: center;
      padding:8% 10%;

      .login-intro {
        flex: 1;
        padding: 40px;
        max-width: 600px;

        .login-title {
          text-align: center;
          font-weight: 600;
          font-size: 30px;
        }

        .login-icons {
          display: flex;
          align-items: center;

          .login-icon {
            padding-left: 5px;
          }
        }
      }

      .login-form {
        height: 350px;
        width: 300px;
        padding: 50px;
        background: white;
        opacity: 0.9;
        box-shadow: 0px 0px 1px #ccc;
        border-radius: 3%;
        overflow: hidden;
        border: 1px solid #ccc;

        .login-brand {
          line-height: 50px;
          margin: 30px 0 40px 0;
          font-size: 22px;
          font-weight: 600;
          letter-spacing: 2px;
          text-transform: uppercase;
          text-align: center;
        }
        .el-button--primary {
          background-color: #4096FF !important;
          border-color: #4096FF !important;
        }
        .register {
          display: flex;
          flex-direction: row-reverse;
          line-height: 40px;
          text-align: center;
          padding-left: 20px;
        }
      }
    }
  }
</style>
